﻿using System;
using System.Security.Permissions;
using Microsoft.Win32.SafeHandles;
using System.Runtime.ConstrainedExecution;

namespace Mattress.Engine.Matlab {
    [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
    internal sealed class SafeArrayPtr : SafeHandleZeroOrMinusOneIsInvalid {
        internal SafeArrayPtr() : base(true) { base.SetHandle(IntPtr.Zero); }

        internal SafeArrayPtr(IntPtr pa) : base(true) { base.SetHandle(pa); }

        internal SafeArrayPtr(IntPtr pa, bool ownsHandle) : base(ownsHandle) { base.SetHandle(pa); }

        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        protected override bool ReleaseHandle() {
            bool flag = false;
            try {
                if (IntPtr.Zero != this.handle) {
                    matrix.mxDestroyArray(this.handle);
                    this.handle = IntPtr.Zero;
                }

                flag = true;
            } catch { }

            return flag;
        }
        
        public override bool IsInvalid {
            get {
                return base.IsClosed || IntPtr.Zero == this.handle;
            }
        }
    }
}
